package net.anzhuo.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 网络请求工具类
 */
public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static List<Map> post(String url, Map<String, String> param) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        for (String key : param.keySet()) {
            list.add(new BasicNameValuePair(key, param.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }
        try {
            HttpResponse execute = httpClient.execute(httpPost);
            List<Map> maps = parseJson2List(execute);
            return maps;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    public static Map getReturn(String url, Map<String, String> param) {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer(url);
        int index = 0;
        for (String key : param.keySet()) {
            if (index == 0) {
                sb.append("?").append(key).append("=").append(param.get(key));
            } else {
                sb.append("&").append(key).append("=").append(param.get(key));
            }
            index++;
        }

        HttpGet get = new HttpGet(sb.toString());
        try {
            HttpResponse execute = httpClient.execute(get);
            Map maps = parseJson2Map(execute);
            return maps;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }

    }

    public static List<Map> get(String url, Map<String, String> param) {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer(url);
        int index = 0;
        for (String key : param.keySet()) {
            if (index == 0) {
                sb.append("?").append(key).append("=").append(param.get(key));
            } else {
                sb.append("&").append(key).append("=").append(param.get(key));
            }
            index++;
        }

        HttpGet get = new HttpGet(sb.toString());
        try {
            HttpResponse execute = httpClient.execute(get);
            List<Map> maps = parseJson2List(execute);
            return maps;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }

    }

    public static String getJson(String url, Map<String, String> param) {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer(url);
        int index = 0;
        for (String key : param.keySet()) {
            if (index == 0) {
                sb.append("?").append(key).append("=").append(param.get(key));
            } else {
                sb.append("&").append(key).append("=").append(param.get(key));
            }
            index++;
        }

        HttpGet get = new HttpGet(sb.toString());
        try {
            HttpResponse execute = httpClient.execute(get);
            String json = EntityUtils.toString(execute.getEntity());
            return json;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }

    }

    public static String getJsonByGet(String url, Map<String, String> param) {
        HttpClient httpClient = new DefaultHttpClient();
        StringBuffer sb = new StringBuffer(url);
        int index = 0;
        for (String key : param.keySet()) {
            if (index == 0) {
                sb.append("?").append(key).append("=").append(param.get(key));
            } else {
                sb.append("&").append(key).append("=").append(param.get(key));
            }
            index++;
        }
        HttpGet get = new HttpGet(sb.toString());
        try {
            HttpResponse execute = httpClient.execute(get);
            if (execute.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(execute.getEntity());
                return json;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    private static Map parseJson2Map(HttpResponse execute) throws Exception{
        if(execute.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(execute.getEntity());
            Map map = JSON.parseObject(json, Map.class);
            if("200".equals(map.get("Status"))){
                return map ;
            }
            return new HashedMap();
        }else{
            return new HashedMap() ;
        }
    }

    private static List<Map> parseJson2List(HttpResponse execute) throws Exception{
        if(execute.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(execute.getEntity());
            Map map = JSON.parseObject(json, Map.class);
            if("200".equals(map.get("Status"))){
                List<Map> result = JSON.parseArray(map.get("Result").toString(), Map.class);
                return result ;
            }
            return new ArrayList<>() ;
        }else{
            return new ArrayList<>() ;
        }
    }

    public static InputStream getInputStreamByUrl(String url) throws Exception{
        HttpClient httpClient  = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse execute = httpClient.execute(get);
        if(execute.getStatusLine() .getStatusCode() ==200){
            return execute.getEntity().getContent();
        }else{
            return null;
        }
    }

}
